
export const PROTOCAL_SEGMENT_BEGIN = '~^'
export const PROTOCAL_SEGMENT_END = '^~'
export const PROTOCAL_SEGMENT_SEPARATOR = '|'
export const PREFIX_ELEMENT_ID = 'XY-'

export function buildElementId(id) {
  return PREFIX_ELEMENT_ID + id
}

export function getElementById(id) {
  return document.getElementById(PREFIX_ELEMENT_ID + id)
}

export function parseToHtml(template, record, consumerArray, id, readonly) {
  if (!consumerArray || !(consumerArray instanceof Array) || !consumerArray.every((e) => e instanceof Function)) {
    throw new Error('未定义的consumerArray，或consumerArray不是数组，或consumerArray的元素不是函数')
  }
  let html = ''
  const protocol = template || ''
  let beginIndex = protocol.indexOf(PROTOCAL_SEGMENT_BEGIN)
  let endIndex = protocol.indexOf(PROTOCAL_SEGMENT_END)
  let index = 0
  while (beginIndex > -1 && endIndex > -1 && endIndex > beginIndex) {
    const segment = template.substring(beginIndex + 2, endIndex)
    // console.log(segment, beginIndex + 2, endIndex, 'parseToHtml')
    let segmentValue = null
    if (record && record instanceof Array) {
      record.forEach(e => {
        if (e.index === index) {
          segmentValue = e.value
          return
        }
      })
    }
    consumerArray.forEach(e => {
      const segmentHtml = e(segment, segmentValue, (id + '-' + index), readonly)
      if (segmentHtml) {
        html += segmentHtml
        return
      }
    })
    index++
    beginIndex = protocol.indexOf(PROTOCAL_SEGMENT_BEGIN, endIndex + 2)
    endIndex = protocol.indexOf(PROTOCAL_SEGMENT_END, endIndex + 2)
  }
  return html
}

export function parseToData(template, record, consumerArray) {
  if (!consumerArray || !(consumerArray instanceof Array) || !consumerArray.every((e) => e instanceof Function)) {
    throw new Error('未定义的consumerArray，或consumerArray不是数组，或consumerArray的元素不是函数')
  }
  const dataArray = []
  const protocol = template || ''
  let beginIndex = protocol.indexOf(PROTOCAL_SEGMENT_BEGIN)
  let endIndex = protocol.indexOf(PROTOCAL_SEGMENT_END)
  let index = 0
  while (beginIndex > -1 && endIndex > -1 && endIndex > beginIndex) {
    const segment = template.substring(beginIndex + 2, endIndex)
    // console.log(segment, beginIndex + 2, endIndex, 'parseToHtml')
    let segmentValue = null
    if (record && record instanceof Array) {
      record.forEach(e => {
        if (e.index === index) {
          segmentValue = e.value
          return
        }
      })
    }
    consumerArray.forEach(e => {
      const segmentData = e(segment, segmentValue)
      if (segmentData) {
        dataArray.push(segmentData)
        return
      }
    })
    index++
    beginIndex = protocol.indexOf(PROTOCAL_SEGMENT_BEGIN, endIndex + 2)
    endIndex = protocol.indexOf(PROTOCAL_SEGMENT_END, endIndex + 2)
  }
  return dataArray
}
